package com.example.sample.activity;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.app.BaseActivity;
import com.example.sample.R;
import com.example.sample.logic.mvp.IPresenter;
import com.example.sample.logic.mvp.IView;

import java.lang.ref.WeakReference;

/**
 * Created by LiangYu on 2018/3/21.
 */
public class MvpTestActivity extends BaseActivity implements IView, View.OnClickListener {

    private TextView tv;
    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mvp_test);
        tv = (TextView)findViewById(R.id.tv);
        btn = (Button)findViewById(R.id.btn);
        btn.setOnClickListener(this);
        btn.setText("握草");
        findViewById(R.id.testWrongSelector).setOnClickListener(this);
        findViewById(R.id.testRightSelector).setOnClickListener(this);
        tv.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn:
                getP().request("onClick");
                break;
            case R.id.testWrongSelector:
                tv.setBackgroundResource(R.drawable.wrong_selector);
                break;
            case R.id.testRightSelector:
                tv.setBackgroundResource(R.drawable.right_selector);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getP().request("onResume");
    }

    public void setText(String text){
        tv.setText(text);
    }

    private IPresenter getP(){
        return new P(this);
    }

    private static class P implements IPresenter{

        private M m = new M();
        private WeakReference<IView> v;

        public P(IView v){
            this.v = new WeakReference<IView>(v);
        }

        public void request(String arg){
            m.request(arg, new M.Callback(){

                @Override
                public void onResult(String result) {
                    if (v.get() != null){
                        v.get().setText(result);
                    }
                }
            });
        }

    }

    private static class M{

        private String data = "This is the data.";

        public interface Callback{
            void onResult(String result);
        }

        public M(){

        }

        public void request(final String arg, final Callback callback){
            final String result = data + " requested by " + arg + ".";
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    callback.onResult(result);
                }
            }, 1000);

        }
    }
}
